package com.xiaoha.pogy.controllers;

import com.xiaoha.pogy.dao.BookRepository;
import com.xiaoha.pogy.dao.BorrowRepository;
import com.xiaoha.pogy.dao.StudentRepository;
import com.xiaoha.pogy.entities.Book;
import com.xiaoha.pogy.entities.Borrow;
import com.xiaoha.pogy.entities.Student;
import com.xiaoha.pogy.services.BookService;
import com.xiaoha.pogy.services.BorrowService;
import com.xiaoha.pogy.services.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("borrows")
public class BorrowController {

    @Autowired
    BorrowService borrowService;

    @Autowired
    BookService bookService;

    @Autowired
    StudentService studentService;

    @GetMapping
    public String disPlayBorrow(Model model){
        List<Borrow> borrows = borrowService.getAll();
        model.addAttribute("borrows",borrows);


        return "borrows/list-borrows";

    }

    @GetMapping("/new")
    public String displayBorrowForm(Model model) {

        Borrow aBorrow = new Borrow();

        List<Book> books = bookService.getAll();
        model.addAttribute("allBooks",books);
        model.addAttribute("borrow",aBorrow);

        List<Student> students = studentService.getAll();
        model.addAttribute("allStudents",students);
        model.addAttribute("borrow",aBorrow);

        return "borrows/new-borrow";
    }



    @PostMapping("/save")
    public String createBorrow(Model model,@RequestParam List<Long> books, Borrow borrow){
        //处理保存到数据库行为
        borrowService.save(borrow);
        //使用重定位
        return "redirect:/borrows";
    }

    @GetMapping("/update")
    public String displayBorrowUpdateFrom(@RequestParam("id") long theId,Model model){

        List<Book> books = bookService.getAll();
        model.addAttribute("allBooks",books);

        List<Student> students = studentService.getAll();
        model.addAttribute("allStudents",students);

        Borrow theBorrow = borrowService.findByBorrowId(theId);
        model.addAttribute("borrow",theBorrow);
        return "borrows/new-borrow";
    }

    @GetMapping("/delete")
    public String deleteBorrow(@RequestParam("id") long theId, Model model){

        Borrow theBorrow = borrowService.findByBorrowId(theId);
        borrowService.delete(theBorrow);
        return "redirect:/givebacks";
    }

}
